<template>
  <div class="app-container">
    <el-row>
      <el-form ref="form" :model="role" label-width="80px">
        <el-form-item label="角色">
          <el-input v-model="role.name"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="role.mark"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="role.tags"></el-input>
        </el-form-item>

        <el-form-item label="用户状态">
          <el-col>
            <el-checkbox v-model="role.superadm">超级管理员</el-checkbox>
            <el-checkbox v-model="role.enable">启用</el-checkbox>
          </el-col>
        </el-form-item>
      </el-form>
    </el-row>

    <el-row>
      <el-table
        :data="routes"
        style="width: 100%; margin-bottom: 20px"
        row-key="meta.id"
        border
        ref="multipleTable"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @select="select_check"
        @select-all="select_all"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="path" label="路径"> </el-table-column>
        <el-table-column prop="meta.title" label="菜单名"> </el-table-column>
        <el-table-column prop="meta.id" label="编号"> </el-table-column>
      </el-table>
    </el-row>

    <el-row style="text-align: center">
      <el-button round type="success" @click="save">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
// import { UserModule } from "@/store/modules/user";
import { roleById, saveRole } from "@/api/role";
@Component({
  name: "sys-edperm",
})
export default class extends Vue {
  private created() {
    this.roleId();
  }

  private checkedChildren(rows: any, checked: boolean) {
    this.toggleSelection(rows, checked);
    for (let i = 0; i < rows.length; i++) {
      if (rows[i].children) {
        this.toggleSelection(rows[i].children, checked);
      }
    }
  }

  private selectAllchecked = false;

  private select_all() {
    this.selectAllchecked = !this.selectAllchecked;
    this.checkedChildren(this.routes, this.selectAllchecked);
  }

  private select_check(selection: any, row: any) {
    row.checked = !row.checked;
    this.toggleSelection([row], row.checked);

    if (row.children) {
      this.checkedChildren(row.children, row.checked);
    }

    if (row.checked) {
      //如果有父级
      if (row.parent) {
        this.toggleSelection([row.parent], row.checked);
      }
    } else if (row.parent) {
      //当前层级是否只有一个选中
      let f =
        row.parent.children.filter((node: any) => node.checked).length == 0;
      if (f) {
        this.toggleSelection([row.parent], row.checked);
      }
    }
  }

  private execChecked(ls: any, rLs: any) {
    rLs.push(...ls.filter((it: any) => it.checked));
    for (let i = 0; i < ls.length; i++) {
      const it = ls[i];
      if (it.children) {
        this.execChecked(it.children, rLs);
      }
    }
  }

  private async save() {
    if (!this.role.name) return;

    let rLs: any = [];
    this.execChecked(this.routes, rLs);

    if (rLs.length > 0) {
      this.role.perms = rLs.map((it: any) => it.meta.id);
    }

    if (!this.role.perms || this.role.perms.length == 0) {
      this.$message.error("请选择角色拥有的菜单！");
      return;
    }

    let d: any = await saveRole(this.role);
    this.$message.success(d.msg);
    this.$router.go(-1);
  }

  // private guid() {
  //   return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
  //     /[xy]/g,
  //     function (c) {
  //       var r = (Math.random() * 16) | 0,
  //         v = c == "x" ? r : (r & 0x3) | 0x8;
  //       return v.toString(16);
  //     }
  //   );
  // }

  //总菜单数
  private mCount = 0;
  setRoleKey(ls: Array<any>, p: any) {
    ls.forEach((it: any) => {
      this.mCount++;
      // it.id = this.guid();
      if (it.children) {
        this.setRoleKey(it.children, it);
        it.children = it.children.filter((it: any) => !it.meta?.hidden);
      }

      if (p) {
        it.parent = p;
      }
    });
  }
  get routes() {
    let ls = (this.$router as any).options.routes.filter(
      (it: any) => !it.meta?.hidden
    );
    this.setRoleKey(ls, null);
    return ls;
  }

  toggleSelection(rows: any, checked: boolean) {
    if (rows) {
      rows.forEach((row: any) => {
        row.checked = checked;
        (<any>this.$refs.multipleTable).toggleRowSelection(row, checked);
      });
    } else {
      (<any>this.$refs.multipleTable).clearSelection();
    }
  }

  private initChecked(ls: any, cLs: any) {
    for (let i = 0; i < ls.length; i++) {
      let it = ls[i];
      it.checked = cLs.includes(it.meta.id);
      if (it.children) {
        this.initChecked(it.children, cLs);
      }
    }
  }

  private role: any = {
    superad: false,
    enable: true,
  };
  private async roleId() {
    //修改
    if (this.$route.query.id) {
      let d = await roleById({ id: this.$route.query.id });
      this.role = d.data;

      //初始化选中状态
      if (this.role.perms) {
        this.initChecked(this.routes, this.role.perms);
        let tls: [] = [];
        this.execChecked(this.routes, tls);
        this.toggleSelection(tls, true);
        this.selectAllchecked = tls.length == this.mCount;
      }
    }
  }
}
</script>